package com.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.web.dao.ProductDao;
import com.web.domain.PageBean;
import com.web.domain.Product;
import com.web.service.BaseService;
import com.web.service.ProductService;
import com.web.service.impl.ProductServiceImpl;
import com.web.utils.BeanFactory;

/**
 * 查询商品详情
 */
@WebServlet("/product") 
public class ProductServlet extends BaseService {
	private static final long serialVersionUID = 1L;

	public String getById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			String pid = request.getParameter("pid");
			ProductService ps = new ProductServiceImpl();
			Product pro = ps.getById(pid);
			
			request.setAttribute("bean", pro);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			request.setAttribute("msg", "暂无此商品信息！程序猿在紧急处理中……");
			return "/jsp/msg.jsp";
		}
		
		return "/jsp/product_info.jsp";
	}
	
	/*
	 * 分页显示
	 */
	public String findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			int pageNumber = 1;
			
			pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
			
			int pageSize = 12;
			String cid = request.getParameter("cid");
			
			ProductService ps = new ProductServiceImpl();
			PageBean<Product> bean = ps.findByPage(pageNumber,pageSize,cid);
			request.setAttribute("page", bean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			request.setAttribute("msg", "查询失败！程序猿在紧急处理中……");
			return "/jsp/msg.jsp";
		}
		return "/jsp/product_list.jsp";
	}
	
	/*
	 * 加入购物车
	 */
	public String addCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			String pid = request.getParameter("pid");
			ProductService ps = new ProductServiceImpl();
			Product pro = ps.getById(pid);
			request.setAttribute("ct", pro);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			request.setAttribute("msg", "添加失败！程序猿在紧急处理中……");
			return "/jsp/msg.jsp";
		}
		return "/jsp/cart.jsp";
	}
	
	public String search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		try {
			String search = request.getParameter("search");
			ProductDao pd = (ProductDao) BeanFactory.getBean("ProductDao");
			List<Product> list = pd.search(search);
			request.setAttribute("pList", list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/jsp/query_list.jsp";
	}
}
